﻿#region - 版 本 注 释 -
/*----------------------------------------------------------------
 * 版权所有 (c) 2024   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-GLJ2Q8J
 * 公司名称：
 * 命名空间：AutoCAD.EntityTool
 * 唯一标识：deda0cdb-e1a5-462b-80c1-e463db9950fa
 * 文件名：LayerTools
 * 当前用户域：DESKTOP-GLJ2Q8J
 * 
 * 创建者：Guo-79991
 * 电子邮箱：799919859@qq.com
 * 创建时间：2024/7/15 12:03:59
 * 版本：V1.0.0
 *
 * 功能描述(Description):
 * 参考文档(Reference):
 * 数据表(Tables):
 * 作者(Author):Guo
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion - 版 本 注 释 -




using Color = Autodesk.AutoCAD.Colors.Color;

namespace AutoCAD.EntityTools
{
    /// <summary>
    /// LayerTools 的摘要说明
    /// </summary>
    public static class LayerTools
    {
        /// <summary>
        /// 获取图层名
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="doc">获取当前活动文档</param>
        /// <returns>图层名字列表</returns>
        public static List<string> GetAllLayerName(this Transaction trans, Document doc)
        {
            // 获取当前数据库
            var db = doc.Database;
            var layerNameList = new List<string>();

            // 打开图层表
            var lt = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

            // 遍历图层表
            foreach (ObjectId id in lt)
            {
                var ltr = trans.GetObject(id, OpenMode.ForRead) as LayerTableRecord;
                // 图层名称
                layerNameList.Add(ltr.Name);
            }
            return layerNameList;
        }
        /// <summary>
        /// 创建一个新的图层
        /// </summary>
        /// <param name="db">Database</param>
        /// <param name="layerName">图层名</param>
        /// <returns>新添加的层表记录的ObjectId</returns>
        public static ObjectId AddLayer(this Database db, string layerName)
        {
            //打开层表
            var lt = db.LayerTableId.GetObject(OpenMode.ForRead) as LayerTable;
            //如果不存在名为layerName的图层，则新建一个图层o
            if (!lt.Has(layerName))
            {
                //定义一个新的图层记录
                var ltr = new LayerTableRecord();
                ltr.Name = layerName;  //设置图层名   
                //切换层表的状态为写为添加的新图层
                lt.UpgradeOpen();
                //将层表记录的信息添加到层表中
                lt.Add(ltr);
                //把层表记录添加到事物处理中
                db.TransactionManager.AddNewlyCreatedDBObject(ltr, true);
                //为了安全，将层表的状态切换为读
                lt.DowngradeOpen();
            }
            return lt[layerName];  //返回新添加的层表记录的ObjectId
        }
        /// <summary>
        /// 添加图层
        /// </summary>
        /// <param name="layName">图层名</param>
        /// <param name="Index">图层颜色index</param>
        public static void AddLayer(this string layName, int Index)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            string LayerName = "";
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite);
                if (lt.Has(layName))
                {
                    ed.WriteMessage($"\n <{layName}>图层已存在！");
                }
                else
                {
                    LayerName = layName;
                    LayerTableRecord ltr = new LayerTableRecord();
                    ltr.Name = LayerName;

                    //short indexColor = (short)(Index % 256);
                    short indexColor = (short)(Index);
                    ltr.Color = Color.FromColorIndex(ColorMethod.ByLayer, indexColor);
                    ObjectId layerId = lt.Add(ltr);
                    trans.AddNewlyCreatedDBObject(ltr, true);
                    db.Clayer = layerId;
                }

                trans.Commit();
            }

        }
        /// <summary>
        /// 修改指定图层的颜色
        /// </summary>
        /// <param name="db">图形数据库</param>
        /// <param name="layerName">图层名</param>
        /// <param name="colorIndex">颜色索引值</param>
        /// <returns>设置图层是否成功</returns>
        public static bool SetLayerColor(this Database db, string layerName, short colorIndex)
        {
            //打开层表
            var lt = db.LayerTableId.GetObject(OpenMode.ForRead) as LayerTable;
            //如果不存在名为layerName的图层，则返回
            if (!lt.Has(layerName)) return false;
            //获取名为layerName的层表记录的Id
            var layerId = lt[layerName];
            //以写的方式打开名为layerName的层表记录
            var ltr = layerId.GetObject(OpenMode.ForWrite) as LayerTableRecord;
            //设置颜色
            ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex);
            //为了安全，将图层的状态切换为读
            ltr.DowngradeOpen();
            return true;  //设置图层颜色成功
        }
        /// <summary>
        /// 获取当前图形中所有的图层
        /// </summary>
        /// <param name="db">图像数据库</param>
        /// <returns>所有图层记录表</returns>
        public static List<LayerTableRecord> GetAllLayers(this Database db)
        {
            //打开层表
            var lt = db.LayerTableId.GetObject(OpenMode.ForRead) as LayerTable;
            //用于返回层表记录的列表
            var ltrs = new List<LayerTableRecord>();
            //遍历层表
            foreach (var id in lt)
            {
                //打开层表记录
                var ltr = id.GetObject(OpenMode.ForRead) as LayerTableRecord;
                ltrs.Add(ltr);  //添加到返回列表中
            }
            return ltrs;    //返回所有的图层记录
        }
        ///// <summary>
        ///// 删除指定名称的图层
        ///// </summary>
        ///// <param name="db">图形数据库</param>
        ///// <param name="layerName">要删除的图层名</param>
        ///// <returns>是否删除成功</returns>
        //public static bool DeleteLayer(this Database db, string layerName)
        //{
        //    //打开层表
        //    var lt = db.LayerTableId.GetObject(OpenMode.ForRead) as LayerTable;
        //    //如果层名为0或Defpoints,则返回（这两个图层不能删除）
        //    if (layerName == "0" || layerName == "Defpoints") return false;
        //    //如果不存在名为 layerName 的图层，则返回
        //    if (!lt.Has(layerName)) return false;
        //    //获取名为layerName的层表记录的Id
        //    var layerId = lt[layerName];
        //    //如果要删除的图层为当前图层，则返回（不能删除当前图层）
        //    if (layerId == db.Clayer) return false;
        //    //打开名为layer Name的层表记录
        //    var ltr = layerId.GetObject(OpenMode.ForRead) as LayerTableRecord;
        //    //如果要删除的图层包含对象或依赖外部参照，则返回（—不能删除这些图层—）
        //    lt.GenerateUsageData();
        //    if (ltr.IsUsed) return false;
        //    //切换层表记录为写状态
        //    ltr.UpgradeOpen();
        //    //删除名为layerName的图层
        //    ltr.Erase(true);
        //    return true; ;//删除图层成功
        //}












        #region 删除图层



        /// <summary>
        /// 删除指定名称的图层
        /// </summary>
        /// <param name="db">图形数据库</param>
        /// <param name="layerName">要删除的图层名</param>
        /// <returns>是否删除成功</returns>
        public static bool DeleteLayer(this Database db, string layerName)
        {
            // 参数验证
            if (db == null)
            {
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage("\n错误：数据库不能为null");
                return false;
            }

            if (string.IsNullOrWhiteSpace(layerName))
            {
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage("\n错误：图层名称不能为空");
                return false;
            }

            // 系统图层不能删除
            if (layerName == "0" || layerName.Equals("Defpoints", StringComparison.OrdinalIgnoreCase))
            {
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误：系统图层 '{layerName}' 不能删除");
                return false;
            }

            Transaction tr = null;
            try
            {
                tr = db.TransactionManager.StartTransaction();

                // 打开层表
                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                if (lt == null)
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage("\n错误：无法获取图层表");
                    return false;
                }

                // 检查图层是否存在
                if (!lt.Has(layerName))
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误：图层 '{layerName}' 不存在");
                    return false;
                }

                // 获取图层ID
                ObjectId layerId = lt[layerName];

                // 检查是否为当前图层
                if (layerId == db.Clayer)
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误：不能删除当前图层 '{layerName}'");
                    return false;
                }

                // 打开图层表记录
                LayerTableRecord ltr = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
                if (ltr == null)
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage("\n错误：无法获取图层记录");
                    return false;
                }

                // 检查图层是否被使用
                lt.GenerateUsageData();
                if (ltr.IsUsed)
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误：图层 '{layerName}' 包含对象或被使用，不能删除");
                    return false;
                }

                // 检查图层是否依赖外部参照
                if (ltr.IsDependent)
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n错误：图层 '{layerName}' 依赖外部参照，不能删除");
                    return false;
                }

                // 检查图层是否被锁定或冻结（虽然不是必须，但提供更好的用户体验）
                if (ltr.IsLocked)
                {
                    Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n警告：图层 '{layerName}' 已被锁定");
                }

                // 切换为写状态并删除
                ltr.UpgradeOpen();
                ltr.Erase(true);

                tr.Commit();

                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n成功删除图层: {layerName}");
                return true;
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                tr?.Abort();
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\nCAD错误：{ex.Message}");
                return false;
            }
            catch (System.Exception ex)
            {
                tr?.Abort();
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n系统错误：{ex.Message}");
                return false;
            }
            finally
            {
                tr?.Dispose();
            }
        }

        /// <summary>
        /// 批量删除图层
        /// </summary>
        /// <param name="db">图形数据库</param>
        /// <param name="layerNames">要删除的图层名称数组</param>
        /// <returns>成功删除的图层数量</returns>
        public static int DeleteLayers(this Database db, params string[] layerNames)
        {
            if (layerNames == null || layerNames.Length == 0)
            {
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage("\n错误：未指定要删除的图层");
                return 0;
            }

            int deletedCount = 0;
            foreach (string layerName in layerNames)
            {
                if (db.DeleteLayer(layerName))
                {
                    deletedCount++;
                }
            }

            Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n成功删除 {deletedCount} 个图层");
            return deletedCount;
        }

        /// <summary>
        /// 删除所有空图层
        /// </summary>
        /// <param name="db">图形数据库</param>
        /// <returns>成功删除的图层数量</returns>
        public static int DeleteAllEmptyLayers(this Database db)
        {
            if (db == null)
            {
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage("\n错误：数据库不能为null");
                return 0;
            }

            int deletedCount = 0;
            Transaction tr = null;

            try
            {
                tr = db.TransactionManager.StartTransaction();

                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                if (lt == null) return 0;

                // 生成使用数据
                lt.GenerateUsageData();

                List<string> layersToDelete = new List<string>();

                // 首先收集所有可删除的图层
                foreach (ObjectId layerId in lt)
                {
                    LayerTableRecord ltr = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
                    if (ltr != null &&
                        ltr.Name != "0" &&
                        !ltr.Name.Equals("Defpoints", StringComparison.OrdinalIgnoreCase) &&
                        layerId != db.Clayer &&
                        !ltr.IsUsed &&
                        !ltr.IsDependent)
                    {
                        layersToDelete.Add(ltr.Name);
                    }
                }

                tr.Commit();
                tr.Dispose();

                // 在事务外删除图层（避免嵌套事务问题）
                foreach (string layerName in layersToDelete)
                {
                    if (db.DeleteLayer(layerName))
                    {
                        deletedCount++;
                    }
                }

                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n成功删除 {deletedCount} 个空图层");
                return deletedCount;
            }
            catch (System.Exception ex)
            {
                tr?.Abort();
                Application.DocumentManager.MdiActiveDocument?.Editor.WriteMessage($"\n删除空图层错误：{ex.Message}");
                return 0;
            }
            finally
            {
                tr?.Dispose();
            }
        }

        /*
         * // 示例1：删除单个图层
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            bool success = db.DeleteLayer("临时图层");

            // 示例2：批量删除图层
            int deletedCount = db.DeleteLayers("图层1", "图层2", "图层3");

            // 示例3：删除所有空图层
            int emptyLayersDeleted = db.DeleteAllEmptyLayers();

            // 示例4：交互式删除图层
            string layerName = GetLayerNameFromUser(); // 自定义获取图层名称的方法
            if (!string.IsNullOrEmpty(layerName))
            {
                db.DeleteLayer(layerName);
            }
         */






        #endregion





























        #region 锁定/解锁图层
        /// <summary>
        /// 解锁指定图层（仅当前事务有效）
        /// </summary>
        public static bool UnlockByLayer(this Document doc, string layerName)
        {
            Database db = doc.Database;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                    if (layerTable == null || !layerTable.Has(layerName))
                    {
                        ($"图层 '{layerName}' 不存在。").CadMessage2(); ;
                        return false;
                    }

                    LayerTableRecord layer = tr.GetObject(layerTable[layerName], OpenMode.ForWrite) as LayerTableRecord;
                    if (layer == null)
                    {
                        ($"无法获取图层 '{layerName}' 的记录。").CadMessage2(); ;
                        return false;
                    }

                    layer.IsLocked = false; // 解锁图层
                    tr.Commit();
                    ($"图层 '{layerName}' 已临时解锁（仅当前事务有效）。").CadMessage2(); ;
                    return true;
                }
            }
            catch (System.Exception ex)
            {
                ($"解锁图层失败: {ex.Message}").CadMessage2(); ;
                return false;
            }
        }

















        /// <summary>
        /// 锁定指定图层
        /// </summary>
        /// <param name="layerNames">要锁定的图层名称数组</param>
        /// <param name="database">图形数据库（如果为null则使用当前数据库）</param>
        /// <returns>成功锁定的图层数量</returns>
        public static int LockLayers(this Document doc, params string[] layerNames)
        {
            if (layerNames == null || layerNames.Length == 0)
            {
                doc?.Editor.WriteMessage("\n错误：未指定图层名称");
                return 0;
            }

            Database db = doc.Database;
            int lockedCount = 0;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    foreach (string layerName in layerNames)
                    {
                        if (string.IsNullOrWhiteSpace(layerName))
                            continue;

                        if (layerTable.Has(layerName))
                        {
                            ObjectId layerId = layerTable[layerName];
                            LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;

                            if (layer != null && !layer.IsLocked)
                            {
                                layer.IsLocked = true;
                                lockedCount++;
                            }
                        }
                        else
                        {
                            doc?.Editor.WriteMessage($"\n警告：图层 '{layerName}' 不存在");
                        }
                    }

                    tr.Commit();

                    if (lockedCount > 0)
                    {
                        doc?.Editor.WriteMessage($"\n成功锁定 {lockedCount} 个图层");
                    }
                }
                catch (System.Exception ex)
                {
                    tr.Abort();
                    doc?.Editor.WriteMessage($"\n锁定图层错误：{ex.Message}");
                }
            }

            return lockedCount;
        }

        /// <summary>
        /// 锁定单个图层
        /// </summary>
        /// <param name="layerName">要锁定的图层名称</param>
        /// <param name="database">图形数据库</param>
        /// <returns>是否成功锁定</returns>
        public static bool LockLayer(this Document doc, string layerName)
        {
            int result = LockLayers(doc, new[] { layerName });
            return result > 0;
        }

        /// <summary>
        /// 通过交互选择锁定图层
        /// </summary>
        /// <returns>成功锁定的图层数量</returns>
        public static int LockLayersInteractive(this Document doc)
        {
            Editor ed = doc.Editor;

            try
            {
                // 获取所有图层名称
                List<string> allLayerNames = GetAllLayerNames(doc.Database);

                if (allLayerNames.Count == 0)
                {
                    ed.WriteMessage("\n当前图形中没有图层");
                    return 0;
                }

                // 创建关键字选项
                PromptKeywordOptions pko = new PromptKeywordOptions("\n选择锁定方式 [全部(ALL)/选择(SELECT)/指定(NAME)]:");
                pko.Keywords.Add("ALL");
                pko.Keywords.Add("SELECT");
                pko.Keywords.Add("NAME");
                pko.Keywords.Default = "SELECT";

                PromptResult pr = ed.GetKeywords(pko);
                if (pr.Status != PromptStatus.OK)
                    return 0;

                string[] layersToLock;

                switch (pr.StringResult)
                {
                    case "ALL":
                        // 锁定所有图层
                        return LockAllLayers(doc);

                    case "SELECT":
                        // 选择要锁定的图层
                        layersToLock = SelectLayersFromList(allLayerNames.ToArray(), "选择要锁定的图层");
                        break;

                    case "NAME":
                        // 输入图层名称
                        layersToLock = GetLayerNamesFromInput();
                        break;

                    default:
                        return 0;
                }

                return LockLayers(doc, layersToLock);
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage($"\n错误：{ex.Message}");
                return 0;
            }
        }

        /// <summary>
        /// 锁定所有图层
        /// </summary>
        /// <param name="database">图形数据库</param>
        /// <returns>成功锁定的图层数量</returns>
        public static int LockAllLayers(this Document doc)
        {
            Database db = doc.Database;
            int lockedCount = 0;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    foreach (ObjectId layerId in layerTable)
                    {
                        LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;
                        if (layer != null && !layer.IsLocked)
                        {
                            layer.IsLocked = true;
                            lockedCount++;
                        }
                    }

                    tr.Commit();
                    doc?.Editor.WriteMessage($"\n成功锁定所有 {lockedCount} 个图层");
                }
                catch (System.Exception ex)
                {
                    tr.Abort();
                    doc?.Editor.WriteMessage($"\n锁定所有图层错误：{ex.Message}");
                }
            }

            return lockedCount;
        }

        /// <summary>
        /// 获取所有图层名称
        /// </summary>
        private static List<string> GetAllLayerNames(this Database database)
        {
            List<string> layerNames = new List<string>();

            using (Transaction tr = database.TransactionManager.StartTransaction())
            {
                LayerTable layerTable = tr.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;

                foreach (ObjectId layerId in layerTable)
                {
                    LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
                    if (layer != null)
                    {
                        layerNames.Add(layer.Name);
                    }
                }

                tr.Commit();
            }

            return layerNames;
        }

        /// <summary>
        /// 从列表中选择图层
        /// </summary>
        private static string[] SelectLayersFromList(string[] layerNames, string promptMessage)
        {
            // 这里可以实现一个图层选择对话框
            // 简化版本：返回前几个图层作为示例
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage($"\n{promptMessage}（当前选择前3个图层作为演示）");

            return layerNames.Take(3).ToArray();
        }

        /// <summary>
        /// 通过输入获取图层名称
        /// </summary>
        private static string[] GetLayerNamesFromInput()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            PromptStringOptions pso = new PromptStringOptions("\n请输入要锁定的图层名称（多个图层用逗号分隔）:");
            PromptResult pr = ed.GetString(pso);

            if (pr.Status == PromptStatus.OK && !string.IsNullOrWhiteSpace(pr.StringResult))
            {
                return pr.StringResult.Split(new[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                                     .Select(name => name.Trim())
                                     .ToArray();
            }

            return new string[0];
        }

        #endregion

        public static List<string> GetAllLayerName(this Document doc)
        {
            var layerNameList = new List<string>();
            // 获取当前数据库
            Database db = doc.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 打开图层表
                var lt = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                // 遍历图层表
                foreach (ObjectId id in lt)
                {
                    var ltr = trans.GetObject(id, OpenMode.ForRead) as LayerTableRecord;
                    // 输出图层名称
                    doc.Editor.WriteMessage(ltr.Name + "\n");
                    layerNameList.Add(ltr.Name);
                }
                trans.Commit();
            }
            return layerNameList;
        }

        /// <summary>
        /// 设置指定实体的图层名称和颜色。
        /// </summary>
        /// <typeparam name="TEntity">实体类型，必须继承自AutoCAD的Entity类。</typeparam>
        /// <param name="entity">要设置图层和颜色的实体对象。</param>
        /// <param name="layerName">要分配给实体的图层名称。</param>
        /// <param name="red">颜色值的红色分量，范围在0到255之间。</param>
        /// <param name="green">颜色值的绿色分量，范围在0到255之间。</param>
        /// <param name="blue">颜色值的蓝色分量，范围在0到255之间。</param>
        /// <param name="trans">当前的事务对象，用于管理对图形数据库的修改。</param>
        /// <param name="doc">当前的文档对象，包含图形数据库和其他文档属性。</param>
        public static void SetLayer<TEntity>(this TEntity entity, string layerName, byte red, byte green, byte blue,
            Transaction trans, Document doc)
            where TEntity : Entity
        {
            // 获取图层表
            LayerTable layerTable = trans.GetObject(doc.Database.LayerTableId, OpenMode.ForRead) as LayerTable;
            if (layerTable == null)
                return;
            // 检查图层是否存在
            if (layerTable.Has(layerName))
            {
                ObjectId layerId = layerTable[layerName];

                entity.LayerId = layerId; // 设置实体所在的图层

                entity.Color = Color.FromRgb(red, green, blue); // 设置实体的颜色
            }
        }

        /// <summary>
        /// 解锁指定图层
        /// </summary>
        /// <param name="layerName">要解锁的图层名称</param>
        /// <returns>操作是否成功</returns>
        public static bool UnlockLayer(this Document document, string layerName)
        {
            if (document == null)
            {
                ("未找到活动文档").CadMessage2();
                return false;
            }

            // 获取数据库对象
            Database database = document.Database;
            Editor ed = document.Editor;

            try
            {
                // 开始事务处理
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    // 获取图层表
                    LayerTable layerTable = transaction.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                    if (layerTable == null)
                    {
                        ("无法获取图层表").CadMessage2();
                        return false;
                    }

                    // 检查图层是否存在
                    if (!layerTable.Has(layerName))
                    {
                        ($"图层 '{layerName}' 不存在").CadMessage2();
                        return false;
                    }

                    // 获取图层记录（以只读方式打开）
                    LayerTableRecord layer = transaction.GetObject(layerTable[layerName], OpenMode.ForRead) as LayerTableRecord;
                    if (layer == null)
                    {
                        ($"无法获取图层 '{layerName}' 的记录").CadMessage2();
                        return false;
                    }

                    // 检查图层是否锁定
                    if (layer.IsLocked)
                    {
                        // 需要以可编辑方式重新打开图层记录
                        transaction.Abort(); // 先中止当前事务
                        using (Transaction unlockTransaction = database.TransactionManager.StartTransaction())
                        {
                            layer = unlockTransaction.GetObject(layerTable[layerName], OpenMode.ForWrite) as LayerTableRecord;
                            if (layer != null)
                            {
                                layer.IsLocked = false;
                                unlockTransaction.Commit();
                                ($"图层 '{layerName}' 已解锁").CadMessage2();
                                ($"图层 '{layerName}' 已解锁").CadMessage2();
                                return true;
                            }
                            else
                            {
                                ($"无法解锁图层 '{layerName}'").CadMessage2();
                                ($"无法解锁图层 '{layerName}'").CadMessage2();
                                return false;
                            }
                        }
                    }
                    else
                    {
                        ($"图层 '{layerName}' 未锁定").CadMessage2();
                        ($"图层 '{layerName}' 未锁定").CadMessage2();
                        return true; // 图层未锁定，视为操作成功
                    }
                }
            }
            catch (System.Exception ex)
            {
                ($"解锁图层时发生错误: {ex.Message}").CadMessage2();
                return false;
            }
        }
        public static void SetLayer<TEntity>(this TEntity entity, Document doc, string layerName, byte red = 255, byte green = 0, byte blue = 0)
    where TEntity : Entity
        {
            using (Transaction trans = doc.Database.TransactionManager.StartTransaction())
            {
                // 获取图层表
                LayerTable layerTable = trans.GetObject(doc.Database.LayerTableId, OpenMode.ForRead) as LayerTable;
                if (layerTable == null)
                    return;
                // 检查图层是否存在
                if (layerTable.Has(layerName))
                {
                    ObjectId layerId = layerTable[layerName];

                    entity.LayerId = layerId; // 设置图层为“墙”

                    entity.Color = Color.FromRgb(red, green, blue); // 设置颜色为红色
                }
            }

        }



        /// <summary>
        /// 检查指定图层上的所有实体中是否至少有一个是参考块
        /// </summary>
        /// <param name="layerName">图层名称</param>
        /// <returns>如果至少有一个实体是参考块，则返回true；否则返回false</returns>
        public static bool HasBlockReferenceOnLayer(this string layerName)
        {
            // 获取当前文档和数据库
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            // 开始事务
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开模型空间块表记录
                BlockTableRecord modelSpace = (BlockTableRecord)tr.GetObject(SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead);

                // 遍历模型空间中的所有实体
                foreach (ObjectId entId in modelSpace)
                {
                    Entity ent = tr.GetObject(entId, OpenMode.ForRead) as Entity;

                    // 检查实体是否在指定图层上
                    if (ent != null && ent.Layer == layerName)
                    {
                        // 如果实体是块引用，则返回true
                        if (ent is BlockReference)
                        {
                            return true;
                        }
                    }
                }

                // 提交事务
                tr.Commit();
            }

            // 如果没有找到任何块引用，则返回false
            return false;
        }
        ///// <summary>
        ///// 选择（通过图层过滤）
        ///// </summary>
        ///// <param name="layerNames"></param>
        ///// <returns></returns>
        //public static SelectionFilter GetSelectionFilterByLayerName(params string[] layerNames)
        //{
        //    var start = new TypedValue((int)DxfCode.Operator, "<or");
        //    var end = new TypedValue((int)DxfCode.Operator, "or>");

        //    var layerTypeValues = layerNames.Select(x => new TypedValue((int)DxfCode.LayerName, x)).ToList();
        //    layerTypeValues.Insert(0, start);
        //    layerTypeValues.Add(end);
        //    return new SelectionFilter(layerTypeValues.ToArray());
        //}





        /// <summary>
        /// 通过图层名称选择实体
        /// </summary>
        /// <param name="layerNames">要选择的图层名称数组</param>
        /// <param name="message">选择提示信息</param>
        /// <param name="allowNone">是否允许不选择任何对象</param>
        /// <returns>选择结果，包含所选实体的ObjectId数组</returns>
        public static ObjectId[] SelectEntitiesByLayer(this Document doc, string[] layerNames, string message = "\n选择对象:", bool allowNone = false)
        {
            Editor ed = doc.Editor;

            try
            {
                // 创建图层过滤的选择过滤器
                SelectionFilter filter = GetSelectionFilterByLayerName(layerNames);

                // 设置选择选项
                PromptSelectionOptions opts = new PromptSelectionOptions
                {
                    MessageForAdding = message,
                    AllowDuplicates = false,
                    RejectObjectsFromNonCurrentSpace = true,
                    RejectObjectsOnLockedLayers = true
                };

                // 执行选择
                PromptSelectionResult selResult = ed.GetSelection(opts, filter);

                if (selResult.Status == PromptStatus.OK)
                {
                    return selResult.Value.GetObjectIds();
                }
                else if (selResult.Status == PromptStatus.Cancel && !allowNone)
                {
                    ed.WriteMessage("\n选择已取消");
                    return null;
                }

                return null;
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage($"\n选择错误: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 创建基于图层名称的选择过滤器
        /// </summary>
        /// <param name="layerNames">图层名称数组</param>
        /// <returns>选择过滤器</returns>
        public static SelectionFilter GetSelectionFilterByLayerName(params string[] layerNames)
        {
            if (layerNames == null || layerNames.Length == 0)
            {
                throw new ArgumentException("至少需要指定一个图层名称");
            }

            var start = new TypedValue((int)DxfCode.Operator, "<or");
            var end = new TypedValue((int)DxfCode.Operator, "or>");

            var layerTypeValues = layerNames
                .Where(name => !string.IsNullOrWhiteSpace(name))
                .Select(x => new TypedValue((int)DxfCode.LayerName, x))
                .ToList();

            if (layerTypeValues.Count == 0)
            {
                throw new ArgumentException("没有有效的图层名称");
            }

            layerTypeValues.Insert(0, start);
            layerTypeValues.Add(end);

            return new SelectionFilter(layerTypeValues.ToArray());
        }






        /// <summary>
        /// 设置实体图层和颜色
        /// </summary>
        /// <param name="entity">要设置的实体</param>
        /// <param name="layerName">图层名称</param>
        /// <param name="red">红色分量 (0-255)</param>
        /// <param name="green">绿色分量 (0-255)</param>
        /// <param name="blue">蓝色分量 (0-255)</param>
        /// <param name="createIfNotExists">如果图层不存在是否创建</param>
        public static void SetEntityLayerAndColor(this Entity entity, string layerName,
            byte red = 0, byte green = 255, byte blue = 0, bool createIfNotExists = true)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            if (string.IsNullOrWhiteSpace(layerName))
                throw new ArgumentException("图层名称不能为空", nameof(layerName));

            try
            {
                Database db = entity.Database;
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    // 获取图层表
                    LayerTable layerTable = transaction.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    // 检查图层是否存在
                    if (!layerTable.Has(layerName))
                    {
                        if (!createIfNotExists)
                        {
                            // 不创建图层，直接使用当前图层
                            transaction.Commit();
                            return;
                        }

                        // 创建新图层
                        CreateNewLayer(transaction, layerTable, layerName, red, green, blue);
                    }

                    // 设置实体的图层
                    Entity entityForWrite = transaction.GetObject(entity.ObjectId, OpenMode.ForWrite) as Entity;
                    if (entityForWrite != null)
                    {
                        entityForWrite.Layer = layerName;
                    }

                    transaction.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ex.Message.CadAlert();
            }
            catch (System.Exception ex)
            {
                $"设置实体图层时发生错误: {ex.Message}".CadAlert();
            }
        }

        /// <summary>
        /// 创建新图层
        /// </summary>
        private static void CreateNewLayer(Transaction transaction, LayerTable layerTable,
            string layerName, byte red, byte green, byte blue)
        {
            LayerTableRecord layerRecord = new LayerTableRecord();

            // 设置图层属性
            layerRecord.Name = layerName;
            layerRecord.Color = Color.FromRgb(red, green, blue);
            layerRecord.IsPlottable = true;
            layerRecord.LineWeight = LineWeight.LineWeight025;

            // 打开图层表用于写入
            layerTable.UpgradeOpen();

            // 添加新图层
            layerTable.Add(layerRecord);
            transaction.AddNewlyCreatedDBObject(layerRecord, true);
        }

        /// <summary>
        /// 安全设置实体图层（不抛出异常）
        /// </summary>
        public static bool TrySetEntityLayerAndColor(this Entity entity, string layerName,
            byte red = 0, byte green = 255, byte blue = 0, bool createIfNotExists = true)
        {
            try
            {
                entity.SetEntityLayerAndColor(layerName, red, green, blue, createIfNotExists);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 批量设置多个实体的图层和颜色
        /// </summary>
        public static void SetEntitiesLayerAndColor(this IEnumerable<Entity> entities, string layerName,
            byte red = 0, byte green = 255, byte blue = 0, bool createIfNotExists = true)
        {
            if (entities == null)
                return;

            // 获取第一个实体的数据库（假设所有实体来自同一个数据库）
            var firstEntity = entities.FirstOrDefault();
            if (firstEntity == null)
                return;

            using (Transaction transaction = firstEntity.Database.TransactionManager.StartTransaction())
            {
                // 确保图层存在
                LayerTable layerTable = transaction.GetObject(firstEntity.Database.LayerTableId, OpenMode.ForRead) as LayerTable;

                if (!layerTable.Has(layerName) && createIfNotExists)
                {
                    CreateNewLayer(transaction, layerTable, layerName, red, green, blue);
                }

                // 设置所有实体的图层
                foreach (var entity in entities)
                {
                    try
                    {
                        Entity entityForWrite = transaction.GetObject(entity.ObjectId, OpenMode.ForWrite) as Entity;
                        if (entityForWrite != null)
                        {
                            entityForWrite.Layer = layerName;
                        }
                    }
                    catch
                    {
                        // 忽略单个实体的错误，继续处理其他实体
                        continue;
                    }
                }

                transaction.Commit();
            }
        }

        /// <summary>
        /// 设置实体图层并使用颜色索引
        /// </summary>
        public static void SetEntityLayerWithColorIndex(this Entity entity, string layerName,
            short colorIndex = 3, bool createIfNotExists = true) // 3 = 绿色
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            try
            {
                Database db = entity.Database;
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    LayerTable layerTable = transaction.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    // 检查图层是否存在
                    if (!layerTable.Has(layerName))
                    {
                        if (!createIfNotExists)
                        {
                            transaction.Commit();
                            return;
                        }

                        // 创建新图层
                        LayerTableRecord layerRecord = new LayerTableRecord();
                        layerRecord.Name = layerName;
                        layerRecord.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex);

                        layerTable.UpgradeOpen();
                        layerTable.Add(layerRecord);
                        transaction.AddNewlyCreatedDBObject(layerRecord, true);
                    }

                    // 设置实体的图层
                    Entity entityForWrite = transaction.GetObject(entity.ObjectId, OpenMode.ForWrite) as Entity;
                    if (entityForWrite != null)
                    {
                        entityForWrite.Layer = layerName;
                    }

                    transaction.Commit();
                }
            }
            catch (System.Exception ex)
            {
                $"设置实体图层时发生错误: {ex.Message}".CadAlert();
            }
        }

        /// <summary>
        /// 确保图层存在（独立方法）
        /// </summary>
        public static bool EnsureLayerExists(Database db, string layerName,
            byte red = 0, byte green = 255, byte blue = 0)
        {
            if (db == null || string.IsNullOrWhiteSpace(layerName))
                return false;

            try
            {
                using (Transaction transaction = db.TransactionManager.StartTransaction())
                {
                    LayerTable layerTable = transaction.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    if (!layerTable.Has(layerName))
                    {
                        CreateNewLayer(transaction, layerTable, layerName, red, green, blue);
                    }

                    transaction.Commit();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public static void SetEntityLayerAndColor<TEntity>(this List<TEntity> entitys, string layerName)
    where TEntity : Entity
        {
            try
            {
                foreach (var entity in entitys)
                {
                    Database db = entity.Database;
                    using (Transaction transaction = db.TransactionManager.StartTransaction())
                    {
                        LayerTable layerTable = (LayerTable)transaction.GetObject(db.LayerTableId, OpenMode.ForRead);

                        // 检查图层是否存在
                        if (!layerTable.Has(layerName))
                        {
                            // 创建新图层
                            using (LayerTableRecord layer = new LayerTableRecord())
                            {
                                // 设置图层名称
                                layer.Name = layerName;

                                // 将图层添加到图层表
                                layerTable.UpgradeOpen();
                                ObjectId layerId = layerTable.Add(layer);
                                transaction.AddNewlyCreatedDBObject(layer, true);

                                // 设置新图层的颜色
                                layer.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(0, 255, 0); // 设置为绿色
                            }
                        }

                        // 设置实体的图层
                        //entity.UpgradeOpen();
                        //entity.LayerId = layerTable[layerName];
                        transaction.Commit();
                    }
                }

            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {

                ex.Message.CadAlert();
            }
        }

        /// <summary>
        /// 更改指定实体的图层名称。如果图层不存在，则创建新的图层。
        /// </summary>
        /// <param name="entity">要更改图层的实体对象。</param>
        /// <param name="layerName">要分配给实体的新图层名称。</param>
        /// <param name="doc">文档对象（可选，如果为null则使用当前活动文档）</param>
        public static bool TryChangeEntityLayer(this Entity entity, string layerName, out string errorMessage,short colorIndex = 3, Document doc = null)
        {
            errorMessage = null;

            if (entity == null)
            {
                errorMessage = "实体对象不能为空";
                return false;
            }

            if (string.IsNullOrWhiteSpace(layerName))
            {
                errorMessage = "图层名称不能为空";
                return false;
            }

            try
            {
                if (doc == null)
                    doc = Application.DocumentManager.MdiActiveDocument;

                if (doc == null)
                {
                    errorMessage = "无法获取有效的文档对象";
                    return false;
                }

                Database db = doc.Database;

                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    // 获取图层表
                    LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    ObjectId layerId;

                    // 检查图层是否存在
                    if (layerTable.Has(layerName))
                    {
                        layerId = layerTable[layerName];
                    }
                    else
                    {
                        // 创建新图层
                        LayerTableRecord newLayer = new LayerTableRecord();
                        newLayer.Name = layerName;
                        newLayer.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex); // 默认 - 绿色

                        layerTable.UpgradeOpen();
                        layerId = layerTable.Add(newLayer);
                        trans.AddNewlyCreatedDBObject(newLayer, true);
                    }

                    // 以写模式打开实体
                    Entity entityForWrite = trans.GetObject(entity.ObjectId, OpenMode.ForWrite) as Entity;
                    if (entityForWrite == null)
                    {
                        errorMessage = "无法以写模式打开实体对象";
                        trans.Abort();
                        return false;
                    }

                    entityForWrite.LayerId = layerId;
                    trans.Commit();
                    return true;
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return false;
            }
        }

        #region 颜色


        /// <summary>
        /// 生成随机的ACI颜色索引（排除0和7）
        /// </summary>
        public static short GetRandomColorIndex()
        {
            var random = new Random(Guid.NewGuid().GetHashCode());

            // 有效范围：1-255（排除7=白色，避免白底不可见）
            short[] excluded = { 0, 7 };
            short index;

            do
            {
                index = (short)random.Next(1, 256);
            } while (excluded.Contains(index));

            return index;
        }

        /// <summary>
        /// 生成随机的深色ACI索引（适用于白底显示）
        /// </summary>
        public static short GetRandomDarkColorIndex()
        {
            // 深色范围：1-6, 8-9（红/黄/绿/青/蓝/洋红/灰）
            short[] darkColors = { 1, 2, 3, 4, 5, 6, 8, 9 };
            return darkColors[new Random().Next(darkColors.Length)];
        }



        /// <summary>
        /// 批量更改多个实体的图层
        /// </summary>
        public static bool ChangeEntitiesLayer(this IEnumerable<Entity> entities, string layerName,short colorIndex = 1,  Document doc = null)
        {
            if (entities == null || !entities.Any())
                return false;

            if (string.IsNullOrWhiteSpace(layerName))
                throw new ArgumentException("图层名称不能为空", nameof(layerName));

            if (doc == null)
                doc = Application.DocumentManager.MdiActiveDocument;

            if (doc == null)
                return false;

            Database db = doc.Database;
            bool success = true;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // 获取或创建图层
                    LayerTable layerTable = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                    ObjectId layerId;

                    if (layerTable.Has(layerName))
                    {
                        layerId = layerTable[layerName];
                    }
                    else
                    {
                        LayerTableRecord newLayer = new LayerTableRecord();
                        newLayer.Name = layerName;
                        newLayer.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex); // 红色

                        layerTable.UpgradeOpen();
                        layerId = layerTable.Add(newLayer);
                        trans.AddNewlyCreatedDBObject(newLayer, true);
                    }

                    // 批量设置实体图层
                    foreach (var entity in entities)
                    {
                        try
                        {
                            Entity entityForWrite = trans.GetObject(entity.ObjectId, OpenMode.ForWrite) as Entity;
                            if (entityForWrite != null)
                            {
                                entityForWrite.LayerId = layerId;
                            }
                        }
                        catch
                        {
                            success = false; // 标记有失败，但继续处理其他实体
                            continue;
                        }
                    }

                    trans.Commit();
                    return success;
                }
                catch
                {
                    trans.Abort();
                    return false;
                }
            }
        }

        #endregion










        /// <summary>
        /// 显示指定图层上的所有实体
        /// </summary>
        /// <param name="layerName">要显示的图层名称</param>
        /// <param name="doc">AutoCAD文档对象</param>
        public static void ShowAllEntitiesOnLayer(string layerName, Document doc)
        {
            Database db = doc.Database;
            Editor ed = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // 1. 检查图层是否存在
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                    if (!lt.Has(layerName))
                    {
                        ed.WriteMessage($"\n图层 '{layerName}' 不存在");
                        return;
                    }

                    // 2. 获取当前空间（模型空间或图纸空间）
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(
                        db.CurrentSpaceId, OpenMode.ForRead);

                    // 3. 收集该图层上的所有实体
                    var entitiesOnLayer = new List<Entity>();
                    foreach (ObjectId id in btr)
                    {
                        if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Entity))))
                        {
                            Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity;
                            if (ent != null && ent.Layer == layerName)
                            {
                                entitiesOnLayer.Add(ent);
                            }
                        }
                    }

                    // 4. 显示实体（取消隐藏和冻结）
                    ShowEntities(entitiesOnLayer, layerName, tr, ed, doc);

                    tr.Commit();
                    ed.WriteMessage($"\n已显示图层 '{layerName}' 上的 {entitiesOnLayer.Count} 个实体");
                }
                catch (System.Exception ex)
                {
                    ed.WriteMessage($"\n错误: {ex.Message}");
                    tr.Abort();
                }
            }
        }

        /// <summary>
        /// 显示实体（设置可见性）
        /// </summary>
        private static void ShowEntities(List<Entity> entities, string layerName, Transaction tr, Editor ed, Document doc)
        {
            // 获取图层表
            LayerTable lt = (LayerTable)tr.GetObject(doc.Database.LayerTableId, OpenMode.ForRead);

            // 检查图层是否存在
            if (!lt.Has(layerName))
            {
                ed.WriteMessage($"\n图层 '{layerName}' 不存在");
                return;
            }

            // 获取图层表记录
            ObjectId layerId = lt[layerName];
            LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForWrite);

            // 1. 确保图层是解冻和打开的
            if (ltr.IsFrozen)
            {
                ltr.IsFrozen = false;
                ed.WriteMessage($"\n已解冻图层 '{layerName}'");
            }

            if (ltr.IsOff)
            {
                ltr.IsOff = false;
                ed.WriteMessage($"\n已打开图层 '{layerName}'");
            }

            // 2. 设置实体可见性
            foreach (Entity ent in entities)
            {
                if (ent.Visible == false)
                {
                    ent.UpgradeOpen();
                    ent.Visible = true;
                }
            }
        }

        /// <summary>
        /// 获取指定图层上的所有实体
        /// </summary>
        /// <param name="layerName">图层名称</param>
        /// <param name="doc">AutoCAD文档对象</param>
        /// <returns>该图层上的所有实体列表</returns>
        public static List<Entity> GetAllEntitiesOnLayer(this Document doc ,  string layerName)
        {
            var entities = new List<Entity>();
            Database db = doc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    // 检查图层是否存在
                    LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
                    if (!lt.Has(layerName))
                    {
                        doc.Editor.WriteMessage($"\n图层 '{layerName}' 不存在");
                        return entities;
                    }

                    // 获取当前空间
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(
                        db.CurrentSpaceId, OpenMode.ForRead);

                    // 收集该图层上的所有实体
                    foreach (ObjectId id in btr)
                    {
                        if (id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(Entity))))
                        {
                            Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity;
                            if (ent != null && ent.Layer == layerName)
                            {
                                entities.Add(ent);
                            }
                        }
                    }

                    tr.Commit();
                }
                catch (System.Exception ex)
                {
                    doc.Editor.WriteMessage($"\n错误: {ex.Message}");
                    tr.Abort();
                }
            }

            return entities;
        }




        #region 显示/隐藏图层上的实体



        private static Dictionary<string, bool> _originalLayerStates = new Dictionary<string, bool>();

        /// <summary>
        /// 显示所有图层
        /// </summary>
        public static void ShowAllLayers(this Document doc)
        {
            Database db = doc.Database;
            Editor ed = doc.Editor;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    if (_originalLayerStates.Count == 0)
                    {
                        // 如果没有保存过状态，则显示所有图层
                        foreach (ObjectId layerId in layerTable)
                        {
                            LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;
                            layer.IsOff = false; // 显示图层
                        }
                        ed.WriteMessage("\n已显示所有图层（无保存的图层状态）");
                    }
                    else
                    {
                        // 恢复保存的图层状态
                        foreach (ObjectId layerId in layerTable)
                        {
                            LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;
                            if (_originalLayerStates.TryGetValue(layer.Name, out bool originalState))
                            {
                                layer.IsOff = originalState;
                            }
                        }
                        ed.WriteMessage("\n已恢复所有图层的原始可见状态");
                    }

                    tr.Commit();
                    ed.Regen(); // 刷新视图
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage($"\n错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 隐藏除选中实体所在图层外的所有图层
        /// </summary>
        public static void HideOtherLayers(this Document doc)
        {
            Database db = doc.Database;
            Editor ed = doc.Editor;

            try
            {
                // 1. 选择实体
                PromptEntityResult per = ed.GetEntity("\n请选择一个实体:");
                if (per.Status != PromptStatus.OK) return;

                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // 2. 获取选中实体所在图层
                    Entity ent = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Entity;
                    string 目标图层 = ent.Layer;

                    // 3. 获取图层表
                    LayerTable layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                    // 4. 保存原始图层状态
                    _originalLayerStates.Clear();
                    foreach (ObjectId layerId in layerTable)
                    {
                        LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord;
                        _originalLayerStates[layer.Name] = layer.IsOff;
                    }

                    // 5. 设置图层可见性
                    foreach (ObjectId layerId in layerTable)
                    {
                        LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForWrite) as LayerTableRecord;
                        layer.IsOff = (layer.Name != 目标图层); // 只显示目标图层
                    }

                    tr.Commit();
                    ed.Regen(); // 刷新视图
                    ed.WriteMessage($"\n已隐藏除 '{目标图层}' 外的所有图层");
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage($"\n错误: {ex.Message}");
            }
        }



        #endregion



    }
}
